package com.yadang.infra.controller;

import com.yadang.infra.base.ApiResult;
import com.yadang.infra.bean.CmmDictDetail;
import com.yadang.infra.bean.CmmDictType;
import com.yadang.infra.bean.dto.CmmDictDto;
import com.yadang.infra.service.CmmDictDetailService;
import com.yadang.infra.service.CmmDictService;
import com.yadang.infra.service.CmmDictTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.invoke.MethodHandles;
import java.util.List;

@Api(tags = "字典表接口")
@RestController
@RequestMapping("/infra/cmmDict")
public class CmmDictController {
    private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    @Autowired
    private CmmDictService cmmDictService;

    @Autowired
    private CmmDictTypeService cmmDictTypeService;

    @Autowired
    private CmmDictDetailService cmmDictDetailService;

    @ApiOperation("条件查询所有的字典数据")
    @PostMapping("selectCmmDetails")
    public ApiResult<?> selectCmmDetail(String cmmDictType, String key, String value) {
        List<CmmDictDto> cmmDictDtoList = cmmDictService.selectCmmDetail(cmmDictType, key, value);
        return ApiResult.success(cmmDictDtoList);
    }

    @ApiOperation("插入字典表信息")
    @PostMapping("insertCmmInfo")
    public ApiResult<?> insertCmmInfo(String cmmDictType, String key, String value, String detailDesc) {

        if (!StringUtils.hasText(cmmDictType)) {
            return ApiResult.fail("字典类型不能为空！");
        }
        if (!StringUtils.hasText(key)){
            return ApiResult.fail("字典原值不能为空！");
        }
        CmmDictType dictType = cmmDictTypeService.selectOneType(cmmDictType);
        if (dictType == null) {
            return ApiResult.fail("不存在这样的字典类型:" + cmmDictType);
        }

        try {
            cmmDictDetailService.insert(dictType, key, value, detailDesc);
        } catch (Exception e) {
            return ApiResult.fail("插入字典数据失败！");
        }
        return ApiResult.success();
    }

}
